package com.boot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.entity.Files;
import com.boot.entity.User;
import com.boot.mapper.FileMapper;
import com.boot.pojo.Result;
import com.boot.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private FileService fileService;
    @Autowired
    private FileMapper fileMapper;

    //文件上传接口
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
        File uploadParentFile = new File(fileUploadPath);
        //判断文件是否存在
        if(!uploadParentFile.exists()){
            uploadParentFile.mkdir();
        }
        String uuid = IdUtil.fastSimpleUUID();
        String fileUuid = uuid +StrUtil.DOT + type;
        File uploadFile = new File(fileUploadPath + fileUuid);
        //获取文件的md5 每个文件的唯一标识,通过对比md5避免上传重复的文件
        String url="";
        //把获取到的文件存储到磁盘中
        file.transferTo(uploadFile);
        String md5=SecureUtil.md5(uploadFile);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("md5",md5);
        List<Files> list = fileService.list(queryWrapper);
        if(list.size()!=0){
            url = list.get(0).getUrl();
            //把获取到的文件删除
            uploadFile.delete();
        }else{
            //如数据库不存在重复文件，则不删除上传的文件
            url = "http://localhost:8989/file/"+fileUuid;
        }

        Files files = new Files();
        files.setName(originalFilename);
        files.setType(type);
        files.setSize(size/1024);
        files.setUrl(url);
        files.setMd5(md5);
        fileService.save(files);
        //存储数据库
        return url;
    }
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable("fileUUID") String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileUUID,"UTF-8"));
        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    //删除单个
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable Integer id){
        Files file = fileService.getById(id);
        file.setIsDelete(true);
        boolean flag = fileService.updateById(file);
        if(flag){
            return new Result().success("执行成功");
        }else{
            return new Result().fail("执行失败");
        }
    }
    //批量删除
    @PostMapping("/dels")
    public Result delete(@RequestBody List<Integer> ids){
        QueryWrapper<Files> queryWrapper = new QueryWrapper();
        queryWrapper.in("id",ids);
        try {
            List<Files> list = fileService.list(queryWrapper);
            list.forEach(one ->{
                one.setIsDelete(true);
                fileService.updateById(one);
            });
        } catch (Exception e) {
            return new Result().fail("删除错误！");
        }
        return new Result().success("执行成功");
    }
    //新增或者更新
    @PostMapping("/update")
    public Result save(@RequestBody Files file){
        boolean flag;
        flag = fileService.saveOrUpdate(file);
        if(flag){
            return new Result().success("修改成功");
        }else{
            return new Result().fail("修改失败");
        }
    }
    //分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name){
        IPage<Files> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",false);
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        IPage<Files> page1 = fileService.page(page,queryWrapper);
        return new Result().add("page",page1);
    }
}
